package com.coolsummer.limiter;

import com.coolsummer.abstracts.Limiter;
import com.coolsummer.utils.DateUtil;

/**
 * @author coolsummer
 * @describe 令牌算法
 * @date 2019/11/18 16:59
 */
public class TokenLimiter extends Limiter{

    /**
     * 当前时间
     */
    private long time;
    /**
     * 当前桶内的令牌
     */
    private double token;
    /**
     * 令牌桶的大小
     */
    private double size;

    public TokenLimiter(double qps) {
        super(qps);
        time = DateUtil.getCounterTime();
        token = qps;
        size = qps;
    }

    @Override
    public synchronized boolean tryAcquire(){
        long current = DateUtil.getCounterTime();
        //创造令牌的数量
        double tokenSize = (double)(current - time) / 1000 * qps;
        token = Math.min(size, tokenSize + token);
        time = current;
        if(token > 0){
            //令牌有剩余
            --token;
            return true;
        } else {
            return false;
        }
    }
}
